package com.itheima.ydd.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.dto.MenuDto;
import com.itheima.ydd.dto.RoleDto;
import com.itheima.ydd.entity.Menu;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.RoleMenu;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.mapper.MenuMapper;
import com.itheima.ydd.mapper.RoleMapper;
import com.itheima.ydd.service.RoleMenuService;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author yan.zhou
 * @since 2022-02-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;


    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserService userService;

    @Override
    public List<String> roleNameList(String role_id) {

        String[] strings = role_id.split(",");
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.in(Role::getId, strings);
        List<Role> roles = this.list(roleLambdaQueryWrapper);
        List<String> roleNameList = CollUtil.getFieldValues(roles, "name", String.class);
        return roleNameList;
    }

    /**
     * 封装该角色的菜单信息
     * @param roleDto
     */
    @Override
    public void authList(RoleDto roleDto) {

        // 查询角色根菜单
        List<Menu> parentList = roleMapper.selectParentList(roleDto.getId());

        if (parentList.isEmpty()) {
            return;
        }

        List<MenuDto> authList = parentList.stream().map(menu -> {
            // 查询每个根菜单的子菜单
            List<MenuDto> childMenuDtoList = selectChildList(roleDto.getId(), menu.getId());
            MenuDto menuDto = new MenuDto();
            BeanUtils.copyProperties(menu, menuDto);
            menuDto.setChildren(childMenuDtoList);
            return menuDto;
        }).collect(Collectors.toList());
        roleDto.setAuthList(authList);
    }

    /**
     * 查询该菜单的子菜单
     * @param id
     * @return
     */
    private List<MenuDto> selectChildList(String roleId, Integer id) {

        List<Menu> childMenuList = roleMapper.selectChildList(roleId, id);
        if (childMenuList.isEmpty()) {
            return null;
        }
        List<MenuDto> menuDtoList = childMenuList.stream().map(menu -> {
            MenuDto menuDto = new MenuDto();
            BeanUtils.copyProperties(menu, menuDto);
            // 递归查询
            menuDto.setChildren(selectChildList(roleId, menu.getId()));
            return menuDto;
        }).collect(Collectors.toList());
        return menuDtoList;
    }

    /**
     * 保存角色及角色包含的菜单
     * @param name
     * @param description
     * @param menuIds
     */
    @Override
    public void saveWithRoleMenu(String name, String description, List<Integer> menuIds) {
        Role role = new Role();
        role.setName(name);
        role.setDescription(description);
        super.save(role);

        // 按条存储
        // for (Integer menuId : menuIds) {
        //     RoleMenu roleMenu = new RoleMenu();
        //     roleMenu.setRoleId(role.getId());
        //     roleMenu.setMenuId(menuId.toString());
        //     roleMenuService.save(roleMenu);
        // }

        // 按集合存储
        List<RoleMenu> roleMenus = new LinkedList<>();
        // List<RoleMenu> roleMenus = new ArrayList<>(menuIds.size());
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(role.getId());
            roleMenu.setMenuId(menuId.toString());
            roleMenus.add(roleMenu);
        }
        roleMenuService.saveBatch(roleMenus);
    }

    /**
     * 删除角色及角色包含的菜单
     * @param id
     */
    @Override
    public void removeWithRoleMenuIfNoUser(String id) {

        {
            // 判断角色是否正在被使用
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getRoleId, "[\"" + id + "\"]");
            if (userService.count(queryWrapper) > 0) {
                throw new BusinessException("该角色下有用户正在使用！无法删除");
            }
        }
        super.removeById(id);
        LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleMenu::getRoleId, id);
        roleMenuService.remove(queryWrapper);
    }

    @Override
    public List<String> roleNameList(List<String> ids) {

        List<Role> roles = super.listByIds(ids);
        return CollUtil.getFieldValues(roles, "name", String.class);
    }



}
